package com.pi.shisan.service.service.impl.next;

import com.pi.shisan.service.annotation.CalcNextTimeType;
import com.pi.shisan.service.constants.ClockTypeEnum;
import com.pi.shisan.service.dto.ClockInfoDTO;
import com.pi.shisan.service.service.ClockNextTimeService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

@CalcNextTimeType(ClockTypeEnum.MOTHER_DAY)
public class MotherDayNextTimeServiceImpl implements ClockNextTimeService {
    //5月的第二个周天
    @Override
    public Long calc(ClockInfoDTO clockInfoDTO) {
        LocalDateTime now = LocalDateTime.now();
        return calcNext(now, 0, clockInfoDTO);
    }

    private Long calcNext(LocalDateTime now, int nextYear, ClockInfoDTO clockInfoDTO) {
        nextYear = nextYear == 0 ? now.getYear() : nextYear;
        if (now.getMonthValue() > 5) {
            nextYear ++;
        }
        LocalDate mayDate = LocalDate.of(nextYear, 5,1);
        int week = mayDate.getDayOfWeek().getValue();
        int day = 7 - week + 8;
        mayDate = LocalDate.of(nextYear, 5, day);
        if (clockInfoDTO.getClkDay() != null) {
            mayDate = mayDate.minusDays(clockInfoDTO.getClkDay());
        }
        LocalDateTime next = mayDate.atTime(clockInfoDTO.getClkHour(), clockInfoDTO.getClkMinute());
        if (next.isAfter(now)) {
            return next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        }
        return calcNext(now, nextYear+1, clockInfoDTO);
    }
}
